package com.jinlia.show.common.core.utils;
import org.locationtech.spatial4j.context.SpatialContext;
import org.locationtech.spatial4j.distance.DistanceUtils;
import org.locationtech.spatial4j.shape.Rectangle;

public class LBSUtils {
    private static final double EARTH_RADIUS = 6378137;


    /**
     * 根据两点间经纬度坐标（double值），计算两点间距离
     *
     * @param lat1 纬度
     * @param lng1 经度
     * @param lat2 纬度
     * @param lng2 经度
     * @return 距离：单位为米
     */
    public static double distanceOfTwoPoints(double lat1, double lng1, double lat2, double lng2) {
        double Lat1 = rad(lat1);
        double Lat2 = rad(lat2);
        double a = Lat1 - Lat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(Lat1) * Math.cos(Lat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    /**
     *
     * @param lon 经度
     * @param lat 维度
     * @param radius 距离 千米
     * @return Rectangle
     */
    public static Rectangle get(Double lon ,Double lat,int radius ) {
        SpatialContext geo = SpatialContext.GEO;
        Rectangle rectangle = geo.getDistCalc().calcBoxByDistFromPt(geo.makePoint(lon, lat), radius * DistanceUtils.KM_TO_DEG, geo, null);
        return rectangle;
    }


    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

//    //测试
//    public static void main(String[] args) {
//        Rectangle rectangle = get(117.158833,31.835198,5);
//        System.out.println(rectangle.getMinX() + " - " + rectangle.getMaxX());  // 经度范围   116.25384300580865 - 116.37121299419135
//        System.out.println(rectangle.getMinY() + " - " + rectangle.getMaxY());  // 纬度范围   39.93876698161192 - 40.02869901838808
//
//        double v = distanceOfTwoPoints(117.158833, 31.835198, 117.125267, 31.819794);
//        System.out.println(v);
//
//    }
}
